<template>
  <el-container class="layout-container">
    <el-aside width="240px" class="layout-aside">
      <div class="logo-container">
        <el-icon :size="32" color="#3a84ff"><Monitor /></el-icon>
        <h2>CMDB资产管理</h2>
      </div>
      
      <el-menu
        :default-active="activeMenu"
        class="layout-menu"
        router
        unique-opened
      >
        <el-sub-menu index="1">
          <template #title>
            <el-icon><Setting /></el-icon>
            <span>CMDB资产管理</span>
          </template>
          
          <el-menu-item index="/hosts">
            <el-icon><Monitor /></el-icon>
            <span>主机管理</span>
          </el-menu-item>
          
          <el-menu-item index="/host-groups">
            <el-icon><FolderOpened /></el-icon>
            <span>主机组管理</span>
          </el-menu-item>
          
          <el-menu-item index="/projects">
            <el-icon><Document /></el-icon>
            <span>项目管理</span>
          </el-menu-item>
          
          <el-menu-item index="/environments">
            <el-icon><Histogram /></el-icon>
            <span>环境管理</span>
          </el-menu-item>
          
          <el-menu-item index="/users">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          
          <el-menu-item index="/user-groups">
            <el-icon><UserFilled /></el-icon>
            <span>用户组管理</span>
          </el-menu-item>
        </el-sub-menu>
        
        <el-sub-menu index="2">
          <template #title>
            <el-icon><Operation /></el-icon>
            <span>运维管理</span>
          </template>
          
          <el-menu-item index="/inspection">
            <el-icon><DataAnalysis /></el-icon>
            <span>系统巡检</span>
          </el-menu-item>
          
          <el-menu-item index="/recipients">
            <el-icon><Message /></el-icon>
            <span>收件人管理</span>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>
    
    <el-container class="layout-main">
      <el-header class="layout-header">
        <div class="header-left">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item>CMDB资产管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{ currentPageTitle }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header-right">
          <span class="time">{{ currentTime }}</span>
          <el-dropdown @command="handleCommand" class="user-dropdown">
            <span class="user-info">
              <el-avatar :size="32" :src="userInfo.avatar" class="user-avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="username">{{ userInfo.username }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item disabled>
                  <div class="user-detail">
                    <el-avatar :size="50" :src="userInfo.avatar" style="margin-bottom: 10px;">
                      <el-icon :size="30"><User /></el-icon>
                    </el-avatar>
                    <div><strong>{{ userInfo.username }}</strong></div>
                    <div class="user-email">{{ userInfo.email || '未设置邮箱' }}</div>
                  </div>
                </el-dropdown-item>
                <el-dropdown-item divided command="profile">
                  <el-icon><User /></el-icon>
                  <span>个人资料</span>
                </el-dropdown-item>
                <el-dropdown-item command="switch">
                  <el-icon><RefreshRight /></el-icon>
                  <span>切换用户</span>
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  <span>退出登录</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <el-main class="layout-content">
        <transition name="fade" mode="out-in">
          <router-view />
        </transition>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { authAPI } from '@/api'

const route = useRoute()
const router = useRouter()
const currentTime = ref('')
const userInfo = ref({
  username: '',
  email: '',
  avatar: ''
})

const activeMenu = computed(() => route.path)
const currentPageTitle = computed(() => route.meta.title || '首页')

// 获取用户信息
const getUserInfo = () => {
  const storedUser = localStorage.getItem('user_info')
  if (storedUser) {
    try {
      userInfo.value = JSON.parse(storedUser)
    } catch (e) {
      console.error('解析用户信息失败', e)
    }
  }
}

// 处理下拉菜单命令
const handleCommand = async (command) => {
  if (command === 'profile') {
    // 进入个人资料页面
    router.push('/profile')
  } else if (command === 'switch') {
    // 切换用户
    ElMessageBox.confirm('确定要切换用户吗？当前用户将退出登录。', '切换用户', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }).then(() => {
      // 清除本地存储
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('user_info')
      
      ElMessage.success('已切换用户，请登录')
      router.push('/login')
    }).catch(() => {
      // 用户取消
    })
  } else if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        const refreshToken = localStorage.getItem('refresh_token')
        if (refreshToken) {
          await authAPI.logout({ refresh: refreshToken })
        }
      } catch (error) {
        console.error('退出登录失败', error)
      } finally {
        // 清除本地存储
        localStorage.removeItem('access_token')
        localStorage.removeItem('refresh_token')
        localStorage.removeItem('user_info')
        
        ElMessage.success('已退出登录')
        router.push('/login')
      }
    }).catch(() => {
      // 用户取消
    })
  }
}

const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

let timer = null

onMounted(() => {
  getUserInfo()
  updateTime()
  timer = setInterval(updateTime, 1000)
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.layout-container {
  width: 100%;
  height: 100vh;
  background: #0a1929;
}

.layout-aside {
  background: #0f1419;
  border-right: 1px solid rgba(58, 132, 255, 0.2);
  height: 100vh;
  overflow-y: auto;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 0 20px;
  border-bottom: 1px solid rgba(58, 132, 255, 0.2);
}

.logo-container h2 {
  color: #3a84ff;
  font-size: 18px;
  margin: 0;
}

.layout-menu {
  border: none;
}

.layout-main {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.layout-header {
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  border-bottom: 1px solid rgba(58, 132, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  color: #fff;
}

.header-left {
  flex: 1;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.time {
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 5px 16px 5px 5px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 20px;
  transition: all 0.3s;
  cursor: pointer;
}

.user-info:hover {
  background: rgba(255, 255, 255, 0.2);
}

.user-avatar {
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.username {
  color: #fff;
  font-size: 14px;
  font-weight: 500;
}

.user-detail {
  padding: 15px 0;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user-email {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.layout-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: #0a1929;
}
</style>
